'''
@Problem description:
Implement atoi to convert a string to an integer.
The function first discards as many whitespace characters as necessary
until the first non-whitespace character is found.
Then, starting from this character, takes an optional initial plus or minus sign followed
by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number,
which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number,
or if no such sequence exists because either str is empty or it contains only whitespace characters,
no conversion is performed.
If no valid conversion could be performed, a zero value is returned.
If the correct value is out of the range of representable values,
INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
字符串转整形，包括符号。无效值返回0，溢出值返回INT_MAX或INT_MIN

@For example:

'''


class Solution:
    '''
    引入状态模式
    '''
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        if not str:
            return 0
        
        minusFlag = False
        INT_MAX = 2147483647
        INT_MIN = -2147483648
        state = -1  # -1,0,1代表 起始态,数值态,结束态
        num = 0
        for i in range(len(str)):
            if (state == -1):
                # ord()是一个将字符转为ASCII的方法，在C语言中是可以直接通过字符拿到ASCII码的，所以这里引用此类库应该没有"循环论证"
                if ((ord(str[i]) == 0x20) or (ord(str[i]) >= 0x09 and ord(str[i]) <= 0x0D)):
                    continue
                elif (str[i] == '+'):
                    state = 0
                elif (str[i] == '-'):
                    state = 0
                    minusFlag = True
                elif (str[i] >= '0' and str[i] <= '9'):
                    state = 0
                    num = num * 10 + (ord(str[i]) - ord('0'))
                else:
                    break
            elif (state == 0):
                if (str[i] >= '0' and str[i] <= '9'):
                    num = num * 10 + (ord(str[i]) - ord('0'))
                else:
                    break

        if (minusFlag):
            if (-num < INT_MIN):
                return INT_MIN
            else:
                return -num
        elif (num > INT_MAX):
            return INT_MAX
        else:
            return num
